import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal, Popover, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import TenantRoleDetail from './components/TenantRoleDetail';
import type { AddItem, TableListItem } from './data';
import {
  addTenantRole,
  queryTenantRoleList,
  querytenantRoleDetail,
  removetenantRole,
} from './service';
import type { ResponseData } from '@/utils/request';

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: AddItem) {
    const hide = message.loading('正在添加');
    try {
      const res: ResponseData<any> = await addTenantRole(fields);
      if (res.code !== 0) {
        message.error(res.message);
        return false;
      }
      hide();
      message.success('添加成功');
      handleAddModalVisible(false);
      // eslint-disable-next-line no-unused-expressions
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
      return false;
    }
  }

  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await removetenantRole(fields);
      hide();
      message.success('删除成功');
      // eslint-disable-next-line no-unused-expressions
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      width: 200,
            dataIndex: 'name',
    },
    {
      title: '编号',
      width: 200,
            dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '权限',
            dataIndex: 'role',
      hideInSearch: true,
      render: (_, record) => {
        const { accesses } = record;
        if (!accesses) return null;
        const showAccesses = accesses.slice(0, 6);
        return (
          // @ts-ignore
          <Popover
            placement="topLeft"
            content={
              <div style={{ maxWidth: 300 }}>
                {accesses.map((item) => (
                  <Tag style={{ margin: 2 }} key={item.id}>
                    {item.name}
                  </Tag>
                ))}
              </div>
            }
          >
            {showAccesses.map((item) => (
              <Tag key={item.id}>{item.name}</Tag>
            ))}
            {showAccesses.length < accesses.length ? '...' : ''}
          </Popover>
        );
      },
    },
    {
      title: '操作',
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setClickItemId(record.id);
        };

        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除客户 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除角色</p>
                <span style={{ fontWeight: 'bolder' }}>{name}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
          });
        };

        return (
          <div>
            <a onClick={onClickDetail}>详情</a>
            <Divider type="vertical" />
            <a onClick={onClickRemove}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper title="客户角色列表">
      <ProTable<TableListItem>
        headerTitle="客户角色列表"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleAddModalVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          // @ts-ignore
          return queryTenantRoleList({ page, pageSize, ...filter });
        }}
        columns={columns}
        rowSelection={false}
      />
      <AddFrom
        modalVisible={addModalVisible}
        onSubmit={(value) => handleAdd(value)}
        onCancel={() => handleAddModalVisible(false)}
      />

      <Drawer
        visible={!!clickItemId && detailVisible}
        onClose={() => setDetailVisible(false)}
        width="50%"
      >
        {!!clickItemId && detailVisible && (
          <TenantRoleDetail id={clickItemId} request={(id) => querytenantRoleDetail({ id })} />
        )}
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
